import Taro ,{ Component } from '@tarojs/taro'
import { View , Button, Picker , Image , Text} from '@tarojs/components'

import { AtInput, AtTextarea} from 'taro-ui'

import './scorePost.scss'
import DataManager from '../../utils/DataManager.js'
import warnIcon from '../../image/ic_warn.png'
import addImage from '../../image/ic_add_image.png'
import locationIcon from '../../image/ic_location.png'
import arrowImage from '../../image/ic_arrow_right.png'

let isCommitEnable = true;
let receiveOptions = [{'name': '到店领取' , 'type' : 0} , {'name': '快递发货' , 'type' : 1} ];
export default class scorePost extends Component{

  config = {
    navigationBarTitleText: '商品录入'
  }

  constructor(props) {
    super(props)
    this.state = {
      isBusiness: '',
      goodsName:'',
      goodsScore:'',
      goodsCount:'',
      startDate:'',
      endDate:'',
      localImageList:[],
      goodsImage:[],
      receiveAddress:'',
      receiveLongitude : '',
      receiveLatitude:'',
      receiveType:0, // 领取方式   0为到店领取，1为发货
    }
  }

  onPullDownRefresh(){
    Taro.stopPullDownRefresh();
  }

  componentDidMount(){
    this.auth = DataManager.getAuthInfo();
    let images = [];
    images.push(addImage);
    this.setState({
      localImageList:images ,
    })
  }

  componentDidShow(){
    this.setState({
      isBusiness:DataManager.getIsBusiness(),
    })
  }

  goToShopRegister = () => {
    Taro.navigateTo({
      url : '/pages/me/shopRegister'
    })
  }

  onGoodNameChange = (goodName) =>{
    this.setState({
      goodsName:goodName
    })
  }

  onGoodScoreChange = (goodScore) =>{
    this.setState({
      goodsScore:goodScore
    })
  }

  onGoodCountChange = (goodCount) =>{
    this.setState({
      goodsCount: goodCount
    })
  }

  handleStartDateChange(value) {
    let val = value.detail.value;
    this.setState({startDate: val})
  }

  handleEndDateChange(value) {
    let val = value.detail.value;
    this.setState({endDate: val})
  }

  onAddressChange = (address) =>{
    this.setState({
      receiveAddress:address
    })
  }

  onChooseLocation = () =>{
    Taro.getSetting({
      success(res){
        if (!res.authSetting['scope.userLocation']) {
          Taro.authorize({
            scope: 'scope.userLocation',
            success() {

            },
          })
        }
      }
    })
    let _this = this;
    Taro.chooseLocation({
      success (res) {
        _this.setState({
          receiveAddress : res.address,
          receiveLongitude : res.longitude,
          receiveLatitude : res.latitude
        })
      }
    })
  }

  onImageClick = (item) => {
    let _this = this;
    // let currentImageList = this.state.localImageList;
    if (item == addImage) {
      Taro.chooseImage({
        sourceType: ['album', 'camera'],
        sizeType:['compressed'],
        count: 1,
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片

          // let tempFilePaths = res.tempFilePaths
          // tempFilePaths = tempFilePaths.concat(currentImageList);
          // if (tempFilePaths.length == 2) {  // 如果有2张图  则表示选完一张了  则添加按钮应移除
          //   tempFilePaths.pop()
          //   return;
          // }

          for (let i = 0 ; i < res.tempFilePaths.length ; i++){
            let tempFilePath = res.tempFilePaths[i]
            let params = {
              filePath: tempFilePath,
              name: 'imageName',
              url: 'https://www.vpin.top/a/stateless/image/fileUpload'
            }
            _this.uploadHeadImage(params)
          }
        }
      })
    }
  }

  uploadHeadImage(params) {

    let baseParams = { platform: 'android_c', loginChannel: 'c' };
    Object.assign(params, baseParams,this.auth);
    params.success = (res) => {
      const d = JSON.parse(res.data)
      if (d.status == 'success') {
        let list = this.state.goodsImage
        let llist = []
        list.push(d.data[0])
        llist.unshift(params.filePath)
        this.setState({goodsImage: list,localImageList: llist})
      }
    }

    params.fail = (obj) => {
      console.log(obj)
    }

    Taro.uploadFile(params);
  }

  onHandleDeleteImage(index){

    let _images = this.state.goodsImage.filter( (ele, _index)=> _index != index )
    let _localImages = this.state.localImageList.filter( (ele, _index)=> _index != index )

    if (_localImages.length == 0){
      _localImages.push(addImage)
    }

    this.setState({
      goodsImage: _images ,
      localImageList:_localImages,
    })
  }

  commitParamsCheck(){
    let checked = false;
    let hint = '';
    if (!this.state.goodsName){
      hint = '请填写商品名称'
    } else if (!this.state.goodsScore){
      hint = '请填写商品积分'
    } else if (!this.state.goodsCount){
      hint = '请填写商品总数量'
    } else if (!this.state.startDate){
      hint = '请选择领取开始日期'
    } else if (!this.state.endDate){
      hint = '请选择领取结束日期'
    } else {
      checked = true;
    }
    if (!checked){
      Taro.showToast({
        title:hint,
        icon:'none'
      })
    }

    return checked;
  }

  onSubmit = () =>{

    if (!isCommitEnable){
      return;
    }

    if (!this.commitParamsCheck()){
      return;
    }

    isCommitEnable = false;

    let data = {
      platform: 'android_c',
      loginChannel: 'c',
      goodsName: this.state.goodsName,
      receiveAddress: this.state.receiveAddress,
      startDate: this.state.startDate + " 00:00:00",
      endDate:this.state.endDate + "  00:00:00",
      goodsImage: this.state.goodsImage[0],
      integral: this.state.goodsScore,
      totalCount: this.state.goodsCount,
      longitude:this.state.receiveLongitude,
      latitude : this.state.receiveLatitude,
      type:this.state.receiveType
    };
    Object.assign(data, this.auth);
    Taro.request({
      url: 'https://www.vpin.top/a/rest/integral/saveIntegralGoods ',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      dataType: 'json',
      data: data,
      success: (obj) => {
        if (obj.data.status == 'fail') {
          Taro.showToast({
            title: '录入失败',
            icon: 'none',
            duration: 1000
          })
        } else {
          Taro.showToast({
            title: '录入成功',
            icon: 'none',
            duration: 1000
          })
          Taro.navigateBack({delta: 1});
        }
        isCommitEnable = true;
      },
      fail: () => {
        Taro.showToast({
          title: '程序异常',
          icon: 'none',
          duration: 1000
        })
        isCommitEnable = true;
      }
    })
  }

  onChooseReceiveType(e) {
    const code = receiveOptions[e.detail.value].type;
    console.log('eeeeeeee          ' + JSON.stringify(e))
    this.setState({receiveType: code})
  }

  render(){

    let nowDate = new Date()
    let start = nowDate.getFullYear() + '-' + nowDate.getMonth() + "-" + nowDate.getDay()

    let startDateShow = this.state.startDate ? this.state.startDate : '点击选择领取开始日期';

    let endDateShow = this.state.endDate ? this.state.endDate : '点击选择领取结束日期';

    let dateTextStyle = this.state.startDate ? 'date-input-text' : 'date-input-text-hint';

    let endDateTextStyle = this.state.endDate? 'date-input-text' : 'date-input-text-hint';

    const inputStyle = 'text-align: right;max-lines:1;margin-top:5px';

    let imageConatiner = this.state.localImageList.map( (item , index) => {
      let imageItemClass =  item == addImage? 'image-item-s' :  'image-item';
      return <View style='position:relative;'><View className={imageItemClass} onClick={this.onHandleDeleteImage.bind(this, index)}>X</View><Image src={item} className='score-post-single-image' mode='aspectFill' onClick={this.onImageClick.bind(this, item)} /></View>
    })

    let catName = '';
    if (this.state.receiveType == 0){
      catName = '到店领取';
    } else if (this.state.receiveType == 1){
      catName = '快递发货'
    }

    return(
      <View className='score-post-container'>
        <View className='score-post-container-sub'>
          {this.state.isBusiness == 0 ?
            <View className='score-not-business-container' onClick={this.goToShopRegister.bind(this)}>
              <Image className='score-post-warn-icon' src={warnIcon}></Image>
              <Text className='score-post-warn-text'>成为商家后才可录入商品，去成为商家 >></Text>
            </View> : null
          }
          <View className='info-form'>
            <AtInput
              style={inputStyle}
              name='goodsName'
              value={this.state.goodsName}
              clear
              title='商品名称'
              type='text'
              placeholder='请填写商品名称'
              border
              maxlength={50}
              onChange={this.onGoodNameChange.bind(this)}
            />
            <AtInput
              style={inputStyle}
              name='goodsScore'
              value={this.state.goodsScore}
              clear
              title='商品积分'
              type='number'
              placeholder='请填写商品积分'
              border
              maxlength={50}
              onChange={this.onGoodScoreChange.bind(this)}
            />
            <AtInput
              style={inputStyle}
              name='goodsCount'
              value={this.state.goodsCount}
              clear
              title='商品总数量'
              type='number'
              placeholder='请填写商品总数量'
              border
              maxlength={50}
              onChange={this.onGoodCountChange.bind(this)}
            />
            <AtInput
              style='text-align: right;max-lines:1'
              name='jobAddress'
              value={this.state.receiveAddress}
              title='领取地址'
              type='text'
              placeholder='请填写领取地址'
              border
              maxlength={50}
              onChange={this.onAddressChange.bind(this)}
            >
              <Image style='width: 20px;height: 20px;' src={locationIcon}  onClick={this.onChooseLocation.bind(this)}></Image>
            </AtInput>
            <View>
              <Picker mode='date' value='YYYY-MM-DD' start={start} onChange={this.handleStartDateChange.bind(this)}>
                <View className='date-input-container'>
                  <Text className='date-input-text'>领取开始日期</Text>
                  <Text className={dateTextStyle}>{startDateShow}</Text>
                </View>
              </Picker>
            </View>
            <View className='date-divider'></View>
            <View>
              <Picker mode='date' value='YYYY-MM-DD' start={start} onChange={this.handleEndDateChange.bind(this)}>
                <View className='date-input-container'>
                  <Text className='date-input-text'>领取结束日期</Text>
                  <Text className={endDateTextStyle}>{endDateShow}</Text>
                </View>
              </Picker>
            </View>
            <View className='date-divider'></View>
            <Picker mode='selector' range={receiveOptions} rangeKey='name' value='0'
                    onChange={this.onChooseReceiveType.bind(this)}>
              <View className='score-post-type-container'>
                <Text className='score-post-type-text'>领取方式</Text>
                <View className='score-post-type-right'>
                  <Text className='score-post-type-text'>{catName}</Text>
                  <Image className='score-post-type-arrow' src={arrowImage}/>
                </View>
              </View>
            </Picker>
            <View className='date-divider'></View>
            <Text className='score-post-upload-text'>请选择商品图片上传</Text>
            <View className='score-post-image-container'>
              {imageConatiner}
            </View>
          </View>
          <View className='post-section' onClick={this.onSubmit.bind(this)}>
            <Button className='score-post-commit'>提交</Button>
          </View>

        </View>
      </View>
    )
  }

}
